//
//  MyView.swift
//  bill
//
//  Created by Eudon on 2025/6/18.
//

import SwiftUI
import UIKit
import CropViewController

// 让URL支持Identifiable，便于.sheet(item:)使用
extension URL: Identifiable {
    public var id: String { absoluteString }
}

// "我"的视图
struct MyView: View {
    // 昵称持久化
    @AppStorage("userName") private var userName: String = "Eudon"
    @State private var showEditName = false
    @State private var tempName = ""
    @State private var showNameAlert = false
    @State private var nameAlertMsg = ""
    // 头像本地存储
    @State private var avatarImage: UIImage? = nil
    @State private var showImagePicker = false
    // 导出相关
    @State private var showExportSheet = false
    @State private var exportStartDate = Calendar.current.date(byAdding: .month, value: -1, to: Date()) ?? Date()
    @State private var exportEndDate = Date()
    @State private var showShare = false
    @State private var exportFileURL: URL? = nil
    @State private var shareItem: URL? = nil
    // 头像文件路径
    private var avatarPath: URL {
        let doc = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        return doc.appendingPathComponent("avatar.png")
    }
    // 敏感词列表
    let sensitiveWords = ["习近平", "共产党", "法轮功", "国家主席", "中国政府", "毛泽东", "江泽民", "周恩来", "李克强", "国家领导人", "暴力", "恐怖", "台独", "疆独", "藏独"]
    // 载入本地头像
    private func loadAvatar() {
        if let data = try? Data(contentsOf: avatarPath), let img = UIImage(data: data) {
            avatarImage = img
        }
    }
    // 保存头像到本地
    private func saveAvatar(_ image: UIImage) {
        if let data = image.pngData() {
            try? data.write(to: avatarPath)
            avatarImage = image
        }
    }
    // 敏感词校验
    private func containsSensitiveWord(_ text: String) -> Bool {
        for word in sensitiveWords {
            if text.contains(word) {
                return true
            }
        }
        return false
    }
    // 获取账单数据（从TransactionStore单例或UserDefaults/文件/环境对象获取）
    private func getAllTransactions() -> [Transaction] {
        // 这里假设用UserDefaults或单例/全局获取，实际项目建议用环境对象
        if let data = try? Data(contentsOf: transactionsFileURL),
           let loaded = try? JSONDecoder().decode([Transaction].self, from: data) {
            return loaded
        }
        return []
    }
    // 账单本地文件路径（与TransactionStore一致）
    private var transactionsFileURL: URL {
        let doc = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        return doc.appendingPathComponent("transactions.json")
    }
    // 生成CSV内容
    private func generateCSV(transactions: [Transaction]) -> String {
        var csv = "日期,类型,分类,金额,备注\n"
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd HH:mm"
        for t in transactions {
            let dateStr = formatter.string(from: t.date)
            let typeStr = t.type == .income ? "收入" : "支出"
            let category = t.category.replacingOccurrences(of: ",", with: " ")
            let note = (t.note ?? "").replacingOccurrences(of: ",", with: " ")
            csv += "\(dateStr),\(typeStr),\(category),\(t.amount),\(note)\n"
        }
        return csv
    }
    // 导出并分享
    private func exportAndShare() {
        let all = getAllTransactions()
        let filtered = all.filter { $0.date >= exportStartDate && $0.date <= exportEndDate }
        let csv = generateCSV(transactions: filtered)
        let fileURL = FileManager.default.temporaryDirectory.appendingPathComponent("账单导出_\(Int(Date().timeIntervalSince1970)).csv")
        try? csv.write(to: fileURL, atomically: true, encoding: .utf8)
        shareItem = fileURL
    }
    var body: some View {
        VStack(spacing: 32) {
            // 头像和昵称
            VStack(spacing: 12) {
                Button(action: { showImagePicker = true }) {
                    Group {
                        if let img = avatarImage {
                            Image(uiImage: img)
                                .resizable()
                        } else {
                            Image(systemName: "person.crop.circle.fill")
                                .resizable()
                                .foregroundColor(.blue)
                        }
                    }
                    .frame(width: 80, height: 80)
                    .clipShape(Circle())
                    .shadow(radius: 4)
                    .overlay(Circle().stroke(Color.blue, lineWidth: 2))
                }
                .buttonStyle(PlainButtonStyle())
                .background(
                    ImagePickerAndCropper(isPresented: $showImagePicker) { cropped in
                        if let cropped = cropped {
                            saveAvatar(cropped)
                        }
                    }
                )
                HStack(spacing: 8) {
                    Text(userName)
                        .font(.title2)
                        .fontWeight(.semibold)
                    Button(action: {
                        tempName = userName
                        showEditName = true
                    }) {
                        Image(systemName: "pencil")
                            .font(.system(size: 16, weight: .medium))
                    }
                }
            }
            .padding(.top, 40)
            // 导出账单按钮
            Button(action: { showExportSheet = true }) {
                HStack {
                    Image(systemName: "square.and.arrow.up")
                    Text("导出账单")
                }
                .font(.headline)
                .padding()
                .frame(maxWidth: .infinity)
                .background(Color.blue.opacity(0.1))
                .cornerRadius(12)
            }
            .padding(.horizontal, 40)
            Spacer()
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(Color(.systemGroupedBackground))
        .navigationTitle("我的")
        .onAppear { loadAvatar() }
        .alert("编辑昵称", isPresented: $showEditName, actions: {
            TextField("昵称", text: $tempName)
            Button("保存") {
                if containsSensitiveWord(tempName) {
                    nameAlertMsg = "昵称包含敏感词，请重新输入。"
                    showNameAlert = true
                } else {
                    userName = tempName
                }
            }
            Button("取消", role: .cancel) {}
        }, message: { Text("") })
        .alert(nameAlertMsg, isPresented: $showNameAlert) {
            Button("确定", role: .cancel) {}
        }
        // 日期范围选择Sheet
        .sheet(isPresented: $showExportSheet) {
            VStack(spacing: 24) {
                Text("选择导出账单的日期范围")
                    .font(.headline)
                    .padding(.top, 24)
                DatePicker("开始日期", selection: $exportStartDate, displayedComponents: .date)
                    .datePickerStyle(.graphical)
                DatePicker("结束日期", selection: $exportEndDate, displayedComponents: .date)
                    .datePickerStyle(.graphical)
                Button("导出") {
                    exportAndShare()
                    showExportSheet = false
                }
                .font(.headline)
                .frame(maxWidth: .infinity)
                .padding()
                .background(Color.blue)
                .foregroundColor(.white)
                .cornerRadius(10)
                Button("取消", role: .cancel) { showExportSheet = false }
                    .padding(.bottom, 24)
            }
            .padding(.horizontal, 24)
        }
        // 分享面板
        .sheet(item: $shareItem) { url in
            ShareSheetActivityView(activityItems: [url])
        }
    }
}

// UIKit图片选择+裁剪封装
struct ImagePickerAndCropper: UIViewControllerRepresentable {
    @Binding var isPresented: Bool
    var onImageCropped: (UIImage?) -> Void
    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }
    func makeUIViewController(context: Context) -> UIViewController {
        let controller = UIViewController()
        controller.view.backgroundColor = .clear
        return controller
    }
    func updateUIViewController(_ uiViewController: UIViewController, context: Context) {
        if isPresented && context.coordinator.imagePicker == nil {
            let picker = UIImagePickerController()
            picker.delegate = context.coordinator
            picker.allowsEditing = false
            context.coordinator.imagePicker = picker
            uiViewController.present(picker, animated: true)
        }
    }
    class Coordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate, CropViewControllerDelegate {
        let parent: ImagePickerAndCropper
        var imagePicker: UIImagePickerController?
        var cropVC: CropViewController?
        init(_ parent: ImagePickerAndCropper) { self.parent = parent }
        func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
            parent.isPresented = false
            picker.dismiss(animated: true)
            imagePicker = nil
        }
        func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
            picker.dismiss(animated: true) {
                self.imagePicker = nil
                if let img = info[.originalImage] as? UIImage {
                    let cropVC = CropViewController(image: img)
                    cropVC.delegate = self
                    cropVC.aspectRatioPreset = .presetSquare
                    cropVC.aspectRatioLockEnabled = true
                    cropVC.resetAspectRatioEnabled = false
                    if let root = UIApplication.shared.windows.first?.rootViewController {
                        root.present(cropVC, animated: true)
                        self.cropVC = cropVC
                    }
                } else {
                    self.parent.isPresented = false
                }
            }
        }
        func cropViewController(_ cropViewController: CropViewController, didFinishCancelled cancelled: Bool) {
            parent.isPresented = false
            cropViewController.dismiss(animated: true)
            cropVC = nil
        }
        func cropViewController(_ cropViewController: CropViewController, didCropToImage image: UIImage, withRect cropRect: CGRect, angle: Int) {
            parent.isPresented = false
            cropViewController.dismiss(animated: true)
            parent.onImageCropped(image)
            cropVC = nil
        }
    }
}

// 替换原ShareSheet为如下实现：
struct ShareSheetActivityView: UIViewControllerRepresentable {
    let activityItems: [Any]
    func makeUIViewController(context: Context) -> UIActivityViewController {
        UIActivityViewController(activityItems: activityItems, applicationActivities: nil)
    }
    func updateUIViewController(_ uiViewController: UIActivityViewController, context: Context) {}
}

#Preview {
    MyView()
} 